//
//  GLSoundToo.m
//  QAQ打飞机
//
//  Created by admin on 15/9/6.
//  Copyright (c) 2015年 gl. All rights reserved.
//

#import "GLSoundToo.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
@interface GLSoundToo()
{
 //背景音乐的对象
    AVAudioPlayer *_musicPlayer;
  //音效字典
    NSDictionary *_soundDict;

}
@end
@implementation GLSoundToo
-(instancetype)init
{
    self =[super init];
    if (self !=nil) {
        NSString*strPath = [[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponent:@"suond.bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:strPath];
        _musicPlayer = [self loadBGMusicWithBundle:bundle];
        _soundDict =[self loadSoundsWithBundle:bundle];
    }



    return self;
}
#pragma mark -私有方法
#pragma mark 加载背景音乐
-(AVAudioPlayer *)loadBGMusicWithBundle:(NSBundle *)bundle
{
    NSString *filePath = [bundle pathForResource:kBGMusic ofType:@"mp3"];
    NSURL *url =[NSURL fileURLWithPath:filePath];
    AVAudioPlayer *musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [musicPlayer setVolume:0.5f];
    [musicPlayer setNumberOfLoops:-1];
    [musicPlayer prepareToPlay];
    
    return musicPlayer;
    
}
#pragma mark 得到声音ID
-(SystemSoundID)loadAudioWithBundle:(NSBundle *)bundle name:(NSString *)name
{
    SystemSoundID soundId;
    NSString *strPath =[bundle pathForResource:name ofType:@"wav"];
    NSURL *url = [NSURL fileURLWithPath:strPath];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundId);

    return soundId;

}
#pragma mark 加载所有音效
-(NSDictionary *)loadSoundsWithBundle:(NSBundle *)bundle
{
    NSMutableDictionary *dataList = [NSMutableDictionary dictionary];
    //名称的数组
    NSArray *arr =@[kBulletAudio,
                    kEnemySmallAudio,
                    kEnemyMidAudio,
                    kEnemyBigAudio,
                    kEnemyBigOutAudio,
                    kHeroOver,
                    kVoice1,
                    kVoice2,
                    kVoice3,
                    kVoice4,
                    kVoice5,
                    kBomb1,
                    kBomb2,
                    kArticle];
    for (NSString*strName in arr)
    {
        SystemSoundID soundId =[self loadAudioWithBundle:bundle name:strName];
        [dataList setObject:@(soundId) forKey:strName];
        
    }

    return dataList;

}
#pragma mark 播放背景音乐
-(void)playBGMusic
{
    [_musicPlayer play];
}
#pragma mark -播放音效
//通过名字播放音效
-(void)playAudioWithName:(NSString *)name
{
    //字典
    SystemSoundID soundId =[_soundDict[name] unsignedIntValue];
    //播放音效
    AudioServicesPlaySystemSound(soundId);

}
@end
